﻿using System;
using System.Collections.Generic;
using System.Drawing;

namespace CSJ2K.Jpc
{
    public class Tile
    {
        public int Precincts
        {
            get
            {
                // TODO: Implement precinct calculation for non-maximal precincts.
                return 1;
            }
        }

        CodeStream CodeStream;

        // Index of the tile in raster order
        public uint Index;

        // Index of tile within the 2D array of tiles
        public uint IndexX;
        public uint IndexY;

        // Top left coordinates of this tile with respect to the reference grid
        public uint X;
        public uint Y;

        // Top left coordinates of the image within this tile with respect to the reference grid
        public uint ImageX;
        public uint ImageY;

        // Width and height of the image area within this tile
        public uint ImageWidth;
        public uint ImageHeight;

        // Current position in the progression.
        public int Layer = 0;
        public int Resolution = 0;
        public int Component = 0;
        public int Precinct = 0;

        public bool[, , ,] PacketCompleted;

        public List<TilePart> TileParts = new List<TilePart>();

        // Create tag-trees for this packet - Should be in Tile
        public TagTree[, , ,] inclusionTree;
        public TagTree[, , ,] zeroBitPlaneTree;
        public byte[, ,][,] lBlockDefaults;

        // TODO: Do most of the calculations on-demand
        public Tile(CodeStream ParentCodeStream, uint Index)
        {
            this.CodeStream = ParentCodeStream;
            this.Index = Index;

            uint ImageWidth = CodeStream.Siz.X - CodeStream.Siz.XO;
            uint ImageHeight = CodeStream.Siz.Y - CodeStream.Siz.YO;

            uint numTilesX = (ImageWidth + CodeStream.Siz.XT - 1) / CodeStream.Siz.XT;
            uint numTilesY = (ImageHeight + CodeStream.Siz.YT - 1) / CodeStream.Siz.YT;

            IndexX = Index % numTilesX;
            IndexY = Index / numTilesY;

            X = CodeStream.Siz.XTO + (IndexX * CodeStream.Siz.XT);
            Y = CodeStream.Siz.YTO + (IndexY * CodeStream.Siz.YT);

            if (CodeStream.Siz.XO > X) ImageX = CodeStream.Siz.XO - CodeStream.Siz.XTO;
            else ImageX = X;

            if (CodeStream.Siz.YO > Y) ImageY = CodeStream.Siz.YO - CodeStream.Siz.YTO;
            else ImageY = Y;

            //if(X+Parent.Siz.XT > Parent.Siz.X) ImageWidth=

            PacketCompleted = new bool[CodeStream.Layers, CodeStream.Resolutions, CodeStream.Components, Precincts];

        }

    }
}
